import mapboxgl, { Map } from "mapbox-gl";
import MapboxLanguage from '@mapbox/mapbox-gl-language';
import basicIcon from "@/assets/images/marker.png"
import { ref, watch } from "vue"
import { customLayer } from "./components/water-layer";
// ----------------
// import { Iotdevice } from "../../api/model"
// ----------------------
mapboxgl.accessToken =
  "pk.eyJ1IjoibXlzb21lIiwiYSI6ImNrMzhkeGM3cTAxM2czZHFldmxkOWQ3N2gifQ.LHODCWg-jAbqBZmOOHtnqQ";
let map: Map;
const isLoad = ref(false)
const markers = []
export interface LngLat {
  longtitude: number
  latitude: number
}

export interface IMarker {
  id: number
  name?: string
  icon?: string
  pos?: LngLat
  size: number,
  properties?: {
    size: number,
    userData: any
  }
}
export interface ILine {
  id: number
  name?: string
  icon?: string
  content?: Array<LngLat>
  properties?: {
    color: string,
    width: number
  }
}
// -----------------------------------
const geojson2 = {
  'type': 'FeatureCollection',
  'features': [
    {
      'type': 'Feature',
      'properties': {
        'message': 'Foo',
        'iconSize': [60, 60]
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [-66.324462, -16.024695]
      }
    },
    {
      'type': 'Feature',
      'properties': {
        'message': 'Bar',
        'iconSize': [50, 50]
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [-61.21582, -15.971891]
      }
    },
    {
      'type': 'Feature',
      'properties': {
        'message': 'Baz',
        'iconSize': [40, 40]
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [-63.292236, -18.281518]
      }
    }
  ]
};
// -------------------------------------

function initMap() {
  if (map) {
    map.remove()
  }
  map = new mapboxgl.Map({
    container: document.getElementById("map"), // container ID
    style: "mapbox://styles/mysome/ck47tr3xs01n61cmdku8zmw9a", // 地图样式URL
    center: [115.86, 28.68], // 地图起始位置
    zoom: 13, // 地图起始比列
  });
  map.addControl(new MapboxLanguage({ defaultLanguage: 'zh-Hans' }));
  map.on('load', () => {
    isLoad.value = true
    // markers.value.forEach(marker=>renderMarker(marker))
    //@ts-ignore
    map.addLayer(customLayer, 'waterway-label')
    watch(() => markers, () => {
      markers.forEach(marker => renderMarker(marker))
    }, {
      immediate: true
    })

    // -------------------------------------

    // setInterval(() => {

    //   Iotdevice({ page: 1, size: 20 }).then((data) => {
    //     // console.log("得到设备数据", data)

    //     for (const marker of data.data.list) {
    //       const el = document.createElement('div');
    //       el.className = 'marker';
    //       el.style.backgroundImage = `url(${marker.icon})`;
    //       el.style.width = `30px`;
    //       el.style.height = `30px`;
    //       el.style.backgroundSize = '100%';
    //       el.innerHTML = "<div>" + `${marker.name}` + "</div>";

    //       new mapboxgl.Marker(el)
    //         .setLngLat([marker.location.x, marker.location.y])
    //         .addTo(map);
    //     }
    //   })
    // }, 5000)
    // ----------------------
  })
}
function addMarker(marker: IMarker) {
  markers.push(marker)
}
function renderMarker(marker: IMarker) {
  console.log("marker", marker)
  if (!marker.icon) {
    marker.icon = basicIcon
  }
  console.log(marker.icon)
  map.loadImage(marker.icon, ((err, image) => {
    if (!map.hasImage(marker.icon)) {
      map.addImage(marker.icon, image)
    }

  }))

  if (!map.getSource('points' + marker.id)) {
    // console.log('点位', a, b)
    map.addSource('points' + marker.id, {
      'type': 'geojson',
      'data': {
        'type': 'FeatureCollection',
        'features': [
          {
            // feature for Mapbox DC
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates':
                [marker.pos.longtitude, marker.pos.latitude]
            },
            properties: {
              title: "123"
            }
          },
        ]
      }
    });
  }

  if (!map.getLayer('pointss' + + marker.id)) {
    // Add a symbol layer
    map.addLayer({
      'id': 'pointss' + + marker.id,
      'type': 'symbol',
      'source': 'points' + + marker.id,
      'layout': {
        'icon-allow-overlap': true,
        'text-allow-overlap': true,
        'icon-image': marker.icon,
        'text-field': ['get', 'title'], //文本内容来源字段
        'text-font': [    //字体
          'Open Sans Semibold',
          'Arial Unicode MS Bold'
        ],
        'text-offset': [0, 30 / marker.size],//设置图标与图标注相对之间的距离
        'text-anchor': 'top', //标记文本相对于定位点的位置
        "text-size": 12,//字号
        "icon-size": marker.size / 30, //图标的大小
      },
      "paint": {
        "text-color": "#fff"
      }
    });
  }
  map.on('click', (e) => {
    console.log(e)
  })

}







export { map, initMap, addMarker, isLoad }